package com.xuan.web;
import com.alibaba.druid.util.StringUtils;
import com.xuan.dao.GameDao;
import com.xuan.model.Game;
import com.xuan.model.Section;
import com.xuan.service.Service;
import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;
import java.io.File;
import java.io.IOException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@WebServlet(urlPatterns = "/servlet/ServiceAction")
@MultipartConfig(maxFileSize = 10*1024*1024)
@SuppressWarnings("all")
public class ServiceAction extends HttpServlet {
    private Service service = new Service();
    private GameDao gameDao = new GameDao();
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("UTF-8");
        response.setContentType("text/html;charset=UTF-8");
        String act = request.getParameter("act");
        if (act == null) {
            act = "list";
        }
        Section section = getServiceTypeFromRequest(request);
        System.out.println(section);
        switch (act) {
            case "addSave":
                Map<String,String> errors = checkServiceType(section);
                if (errors.size() > 0) {
                    request.setAttribute("act","addSave");
                    request.setAttribute("section",section);
                    request.setAttribute("errors",errors);
                    request.setAttribute("games",gameDao.getAll());
                    forward(request,response,"请填写完整信息","/WEB-INF/jsp/serviceType1/input.jsp");
                    return;
                }
                if (service.add(section)) {
                    forward(request,response,"保存成功","ServiceTypeAction?act=list");
                }else {
                    request.setAttribute("act","addSave");
                    request.setAttribute("section",section);
                    forward(request,response,"保存失败","/WEB-INF/jsp/serviceType1/input.jsp");
                }
                break;
            case "updateSave":
                String id = request.getParameter("id");
                Section section1 = service.get(Integer.parseInt(id));
                if (service.update(section)) {
                    forward(request,response,"修改成功","ServiceTypeAction?act=list");
                }else {
                    request.setAttribute("act","addSave");
                    request.setAttribute("section",section);
                    forward(request,response,"修改失败","/WEB-INF/jsp/serviceType1/input.jsp");
                }
                break;
            default:
                int page = 1;
                String size = getServletContext().getInitParameter("pageSize");
                String page1 = request.getParameter("page");
                if (page1 != null) {
                    page = Integer.parseInt(page1);
                }
            request.setAttribute("page",page);
                request.setAttribute("games",gameDao.getAll());
                request.setAttribute("lastpage",service.getPageSize(Integer.parseInt(size)));
                forward(request,response,"sections",
                        service.getAll(Integer.parseInt(size),page),"/WEB-INF/jsp/serviceType1/list.jsp");
        }
    }

    private Map<String,String> checkServiceType(Section section) {
        String msg = "";
        Map<String,String> map = new HashMap<>();
        if (StringUtils.isEmpty(section.getName())) {
            map.put("name","请输入昵称");
        }
        if (StringUtils.isEmpty(section.getLoc())) {
            map.put("loc","请输入地点");
        }
        if (StringUtils.isEmpty(section.getAcc_img())) {
            map.put("acc_img","请上传图片");
        }
        if (section.getPrice() == 0) {
            map.put("price","请输入价格");
        }
        if (StringUtils.isEmpty(section.getDan())) {
            map.put("dan","请选择段位");
        }
        return map;
    }

    private Section getServiceTypeFromRequest(HttpServletRequest request) throws IOException, ServletException {
        Section section = new Section();
        String id = request.getParameter("id");
        if (!StringUtils.isEmpty(id)) {
            section.setId(Integer.parseInt(id));
        }
        String name = request.getParameter("name");
        if (name != null) {
            section.setName(name);
        }
        String level = request.getParameter("level");
        if (!StringUtils.isEmpty(level)) {
            section.setLevel_(Double.valueOf(level));
        }else {
            section.setLevel_(0);
        }
        String count = request.getParameter("order_count");
        if (!StringUtils.isEmpty(count)) {
            section.setOrder_count(Integer.parseInt(count));
        }else {
            section.setOrder_count(0);
        }
        section.setLoc(request.getParameter("loc"));
//        String uploadDir = getServletContext().getInitParameter("uploadDir");
//        String realPath = getServletContext().getRealPath(uploadDir);
        String realPath = getServletContext().getInitParameter("imgPath");
        File file = new File(realPath);
        if (!file.exists()) {
            file.mkdirs();
        }
        Part acc_img = request.getPart("acc_img");
        if (acc_img != null && acc_img.getSize() > 0) {
            String submitFileName = acc_img.getSubmittedFileName();
            String fileName = coverFileName(submitFileName);
            section.setAcc_img("/img/"+fileName);
            acc_img.write(realPath+"\\"+fileName);
        }
        section.setMessage(request.getParameter("message"));
        String price = request.getParameter("price");
        if (!StringUtils.isEmpty(price)) {
            section.setPrice(Integer.parseInt(price));
        }
        String dan = request.getParameter("dan");
        if (dan != null) {
            section.setDan(dan);
        }
        String game_name = request.getParameter("game_name");
        Game game = new GameDao().get(game_name);
        section.setGame_id(game);
        return section;
    }

    private String coverFileName(String submitFileName) {
        DateFormat dateFormat = new SimpleDateFormat("-yyyyMMddhhmmss");
        String temp = dateFormat.format(new Date());
        int pos = submitFileName.lastIndexOf(".");
        return submitFileName.substring(0,pos)+temp+submitFileName.substring(pos);
    }

    private void forward(HttpServletRequest request, HttpServletResponse response, String key,Object value, String url) throws ServletException, IOException {
        request.setAttribute(key, value);
        request.getRequestDispatcher(url).forward(request, response);
    }

    private void forward(HttpServletRequest request, HttpServletResponse response, String msg, String url) throws ServletException, IOException {
        request.setAttribute("msg", msg);
        request.getRequestDispatcher(url).forward(request, response);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req,resp);
    }
}
